# -*- coding: utf-8 -*-

"""
Date: 2023/2/27 13:53
Author: Darker
"""
import os
import smtplib
import time
import traceback
from typing import Dict, NoReturn

from requests import exceptions

from config import conf
from log import logger
from utils.tapd_utils import tapd
from utils.ui_utils import ui
from utils import g, email_utils


def setUp() -> NoReturn:
    """初始化工作"""
    # 检查网络是否可用
    tapd.check_network_process()

    # 读取配置文件
    g.configData = configData = conf.get_option()

    # 加载UI布局
    ui.init_window(configData)

    g.oldId = configData.get("id")
    g.oldIterationId = configData.get("iterationId")
    g.oldReleaseId = configData.get("releaseId")
    g.idName = configData.get("listId").split("_toolFlag_")
    g.iterationUpdate = configData.get("listIteration").split("_toolFlag_")
    g.releaseUpdate = configData.get("listReleaseId").split("_toolFlag_")
    g.win2Active = False
    g.windowActive = False
    g.timer = False
    g.setEnd = 0


def process_config(updateConfigFlag: bool, configData: Dict):
    """
    处理配置文件，根据UI操作决定是否更新配置文件内容
    :return:
    """
    if updateConfigFlag:
        for section, data in configData.items():
            for key, value in data.items():
                conf.modify_config(section=section, key=key, value=value)


def tearDown():
    """清理缓存数据"""
    for pic in os.listdir(conf.pictureDir):
        if pic.endswith(".png"):
            os.remove(os.path.join(conf.pictureDir, pic))


def run():
    try:
        setUp()  # 初始化检查
        while True:
            if ui.event_handler() == "break":
                break
        ui.window.close()
    except (exceptions.ConnectionError, exceptions.RequestException):
        logger.error("连接错误，请检查网络; 确认是否开启代理工具, 如fiddler、VPN")
        logger.error(traceback.format_exc())
    except exceptions.ConnectTimeout:
        logger.error("连接超时，请稍后重试")
        logger.error(traceback.format_exc())
    except smtplib.SMTPAuthenticationError:
        logger.error("请确认邮箱账户正确性")
    except Exception:
        traceback.print_exc()
        logger.error(traceback.format_exc())
    finally:
        # 还原TAPD缺陷显示字段 TODO 本次先不处理
        tearDown()


if __name__ == '__main__':
    run()
